<template>
  <div class="interview-calendar">
    <!-- 日历头部 -->
    <div class="calendar-header">
      <div class="header-controls">
        <el-button @click="previousMonth" :icon="ArrowLeft" circle />
        <div class="current-month">
          <h3>{{ currentMonthText }}</h3>
        </div>
        <el-button @click="nextMonth" :icon="ArrowRight" circle />
      </div>
      <div class="header-actions">
        <el-button @click="goToToday" size="small">今天</el-button>
        <el-button @click="refreshData" :loading="loading" size="small">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 图例 -->
    <div class="calendar-legend">
      <div class="legend-item" v-for="type in interviewTypes" :key="type.value">
        <div class="legend-color" :style="{ backgroundColor: type.color }"></div>
        <span class="legend-text">{{ type.label }}</span>
      </div>
    </div>

    <!-- 日历网格 -->
    <div class="calendar-grid" v-loading="loading">
      <!-- 星期标题 -->
      <div class="weekdays">
        <div class="weekday" v-for="day in weekdays" :key="day">
          {{ day }}
        </div>
      </div>

      <!-- 日期网格 -->
      <div class="days-grid">
        <div
          v-for="day in calendarDays"
          :key="day.date"
          class="day-cell"
          :class="{
            'other-month': !day.isCurrentMonth,
            'today': day.isToday,
            'has-interviews': day.interviews.length > 0
          }"
        >
          <div class="day-number">{{ day.day }}</div>
          
          <!-- 面试事件 -->
          <div class="interviews-container" v-if="day.interviews.length > 0">
            <div
              v-for="interview in day.interviews.slice(0, maxEventsPerDay)"
              :key="interview.id"
              class="interview-event"
              :style="{ backgroundColor: getInterviewColor(interview.interview_type) }"
              @click="handleInterviewClick(interview)"
              :title="getInterviewTooltip(interview)"
            >
              <div class="event-time">{{ formatTime(interview.scheduled_time) }}</div>
              <div class="event-title">{{ interview.title }}</div>
              <div class="event-student">{{ interview.student_name }}</div>
            </div>
            
            <!-- 更多事件指示器 -->
            <div
              v-if="day.interviews.length > maxEventsPerDay"
              class="more-events"
              @click="showMoreEvents(day)"
            >
              +{{ day.interviews.length - maxEventsPerDay }} 更多
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 更多事件弹窗 -->
    <el-dialog
      v-model="showMoreDialog"
      :title="`${selectedDay?.date} 的面试安排`"
      width="600px"
    >
      <div class="more-events-list">
        <div
          v-for="interview in selectedDay?.interviews || []"
          :key="interview.id"
          class="event-item"
          @click="handleInterviewClick(interview)"
        >
          <div class="event-info">
            <div class="event-header">
              <span class="event-time">{{ formatTime(interview.scheduled_time) }}</span>
              <el-tag
                :type="getStatusTagType(interview.status)"
                size="small"
              >
                {{ getStatusText(interview.status) }}
              </el-tag>
            </div>
            <div class="event-title">{{ interview.title }}</div>
            <div class="event-details">
              <span>学生：{{ interview.student_name }}</span>
              <span v-if="interview.location">地点：{{ interview.location }}</span>
            </div>
          </div>
          <div
            class="event-color-bar"
            :style="{ backgroundColor: getInterviewColor(interview.interview_type) }"
          ></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowRight, Refresh } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  interviews: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  maxEventsPerDay: {
    type: Number,
    default: 3
  }
})

// Emits
const emit = defineEmits(['refresh', 'interview-click', 'month-change'])

// 响应式数据
const currentDate = ref(new Date())
const showMoreDialog = ref(false)
const selectedDay = ref(null)

// 星期标题
const weekdays = ['日', '一', '二', '三', '四', '五', '六']

// 面试类型配置
const interviewTypes = [
  { value: 'practice', label: '练习面试', color: '#67C23A' },
  { value: 'mock', label: '模拟面试', color: '#409EFF' },
  { value: 'assessment', label: '评估面试', color: '#E6A23C' },
  { value: 'career_guidance', label: '职业指导', color: '#F56C6C' }
]

// 计算属性
const currentMonthText = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth() + 1
  return `${year}年${month}月`
})

const calendarDays = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  
  // 获取当月第一天和最后一天
  const firstDay = new Date(year, month, 1)
  const lastDay = new Date(year, month + 1, 0)
  
  // 获取第一周的开始日期（可能是上个月的日期）
  const startDate = new Date(firstDay)
  startDate.setDate(startDate.getDate() - firstDay.getDay())
  
  // 获取最后一周的结束日期（可能是下个月的日期）
  const endDate = new Date(lastDay)
  endDate.setDate(endDate.getDate() + (6 - lastDay.getDay()))
  
  const days = []
  const currentDateObj = new Date(startDate)
  
  while (currentDateObj <= endDate) {
    const dateStr = formatDate(currentDateObj)
    const dayInterviews = props.interviews.filter(interview => {
      const interviewDate = new Date(interview.scheduled_time)
      return formatDate(interviewDate) === dateStr
    })
    
    days.push({
      date: dateStr,
      day: currentDateObj.getDate(),
      isCurrentMonth: currentDateObj.getMonth() === month,
      isToday: isToday(currentDateObj),
      interviews: dayInterviews
    })
    
    currentDateObj.setDate(currentDateObj.getDate() + 1)
  }
  
  return days
})

// 方法
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const formatTime = (datetime) => {
  const date = new Date(datetime)
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

const isToday = (date) => {
  const today = new Date()
  return formatDate(date) === formatDate(today)
}

const getInterviewColor = (type) => {
  const typeConfig = interviewTypes.find(t => t.value === type)
  return typeConfig ? typeConfig.color : '#909399'
}

const getStatusTagType = (status) => {
  const statusMap = {
    'scheduled': 'warning',
    'in_progress': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'expired': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'scheduled': '已安排',
    'in_progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消',
    'expired': '已过期'
  }
  return statusMap[status] || status
}

const getInterviewTooltip = (interview) => {
  return `${formatTime(interview.scheduled_time)} - ${interview.title}\n学生：${interview.student_name}${interview.location ? `\n地点：${interview.location}` : ''}`
}

const previousMonth = () => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() - 1)
  currentDate.value = newDate
  emit('month-change', newDate)
}

const nextMonth = () => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() + 1)
  currentDate.value = newDate
  emit('month-change', newDate)
}

const goToToday = () => {
  const today = new Date()
  currentDate.value = today
  emit('month-change', today)
}

const refreshData = () => {
  emit('refresh')
}

const handleInterviewClick = (interview) => {
  emit('interview-click', interview)
}

const showMoreEvents = (day) => {
  selectedDay.value = day
  showMoreDialog.value = true
}

// 监听当前日期变化
watch(currentDate, (newDate) => {
  emit('month-change', newDate)
}, { immediate: true })
</script>

<style lang="scss" scoped>
.interview-calendar {
  background: var(--el-bg-color);
  border-radius: 8px;
  overflow: hidden;
  transition: background-color 0.3s ease;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--el-border-color);
  background: var(--el-bg-color-page);
  transition: all 0.3s ease;
  
  .header-controls {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .current-month h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.calendar-legend {
  display: flex;
  gap: 24px;
  padding: 16px 24px;
  background: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color);
  transition: all 0.3s ease;

  .legend-item {
    display: flex;
    align-items: center;
    gap: 8px;

    .legend-color {
      width: 12px;
      height: 12px;
      border-radius: 2px;
    }

    .legend-text {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.calendar-grid {
  .weekdays {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    background: var(--el-bg-color-page);
    border-bottom: 1px solid var(--el-border-color);
    transition: all 0.3s ease;

    .weekday {
      padding: 12px;
      text-align: center;
      font-weight: 600;
      color: var(--el-text-color-secondary);
      font-size: 14px;
    }
  }
  
  .days-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    
    .day-cell {
      min-height: 120px;
      border-right: 1px solid var(--el-border-color);
      border-bottom: 1px solid var(--el-border-color);
      padding: 8px;
      position: relative;
      cursor: pointer;
      transition: all 0.3s ease;
      background: var(--el-bg-color);

      &:hover {
        background-color: var(--el-fill-color-lighter);
      }

      &.other-month {
        background-color: var(--el-fill-color-light);
        color: var(--el-text-color-disabled);
      }

      &.today {
        background-color: var(--el-color-primary-light-9);

        .day-number {
          background: var(--el-color-primary);
          color: white;
          border-radius: 50%;
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      
      .day-number {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 4px;
      }
      
      .interviews-container {
        .interview-event {
          margin-bottom: 2px;
          padding: 2px 4px;
          border-radius: 3px;
          font-size: 11px;
          line-height: 1.2;
          color: white;
          cursor: pointer;
          transition: opacity 0.2s;
          
          &:hover {
            opacity: 0.8;
          }
          
          .event-time {
            font-weight: 600;
          }
          
          .event-title {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .event-student {
            font-size: 10px;
            opacity: 0.9;
          }
        }
        
        .more-events {
          font-size: 11px;
          color: var(--el-color-primary);
          cursor: pointer;
          text-align: center;
          padding: 2px;
          transition: all 0.3s ease;

          &:hover {
            background-color: var(--el-color-primary-light-9);
            border-radius: 3px;
          }
        }
      }
    }
  }
}

.more-events-list {
  .event-item {
    display: flex;
    align-items: center;
    padding: 12px;
    border: 1px solid var(--el-border-color);
    border-radius: 6px;
    margin-bottom: 8px;
    cursor: pointer;
    background: var(--el-bg-color);
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary);
      box-shadow: 0 2px 8px var(--el-box-shadow-light);
    }
    
    .event-info {
      flex: 1;
      
      .event-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 4px;
        
        .event-time {
          font-weight: 600;
          color: var(--el-color-primary);
        }
      }
      
      .event-title {
        font-weight: 600;
        margin-bottom: 4px;
      }
      
      .event-details {
        display: flex;
        gap: 16px;
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
    }
    
    .event-color-bar {
      width: 4px;
      height: 40px;
      border-radius: 2px;
      margin-left: 12px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .calendar-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    
    .header-controls,
    .header-actions {
      justify-content: center;
    }
  }
  
  .calendar-legend {
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .day-cell {
    min-height: 80px;
    padding: 4px;
    
    .interview-event {
      font-size: 10px;
      padding: 1px 2px;
      
      .event-student {
        display: none;
      }
    }
  }
}
</style>
